package com.zcareu.logServ.service;

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.Machine;
import com.aliyun.openservices.log.common.MachineList;
import com.aliyun.openservices.log.exception.LogException;
import com.zcareu.logServ.entity.Agent;
import com.zcareu.logServ.repo.AgentRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.zcareu.logServ.service.AliyunConstant.*;

@Service
public class AgentServ {

    private final static Client CLIENT = new Client(HOST, ACCESS_ID, ACCESS_KEY);

    @Autowired
    private AgentRepo agentRepo;

    public boolean addAgent(String uuid, String _hostname, String _machineGroup, String _displayName, String identifier) {
        Agent agent = new Agent();

        agent.setUUID(uuid);
        agent.setHostname(_hostname);
        agent.setDisplayName(_displayName);

        agentRepo.save(agent);

        try {
            return !CLIENT.AddMachineIntoMahineGroup(PROJECT, _machineGroup,
                    new MachineList(new ArrayList<String>() {{
                        add(identifier);
                    }})
            ).GetAllHeaders().isEmpty();
        } catch (LogException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public List<String> getGroups() {
        try {
            return CLIENT.ListMachineGroup(PROJECT).GetMachineGroups();
        } catch (LogException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public List<Map<String, Object>> getAgents(String machineGroup) {
        Map<String, Map<String, Object>> machines = new LinkedHashMap<>();

        try {
            for (Machine machine : CLIENT.ListMachines(PROJECT, machineGroup, 0, Integer.MAX_VALUE).GetMachines()) {
                machines.put(machine.GetMachineUniqueId(), machine.ToJsonObject());
            }

            for (Agent agent : agentRepo.findAllByUUIDIn(machines.keySet())) {
                Map<String, Object> machine = machines.get(agent.getUUID());
                machine.put("id", agent.getId());
                machine.put("hostname", agent.getHostname());
                machine.put("displayName", agent.getDisplayName());
            }
        } catch (LogException e) {
            e.printStackTrace();
        }

        return new LinkedList<>(machines.values());
    }
}
